package top.ochiamalu.aioj.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import top.ochiamalu.aioj.common.ErrorCode;
import top.ochiamalu.aioj.constant.ModifyPhoneConstants;
import top.ochiamalu.aioj.enums.ModifyPhoneEnum;
import top.ochiamalu.aioj.exception.BusinessException;
import top.ochiamalu.aioj.service.ValidateCodeService;
import top.ochiamalu.aioj.util.CodeUtils;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 验证代码服务impl
 *
 * @author ochiamalu
 * @date 2025/04/09
 */
@Service
@Slf4j
public class ValidateCodeServiceImpl implements ValidateCodeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean generateModifyPhoneCode(Integer type, String phone) {
        if (!phone.matches("0?(13|14|15|18|17)[0-9]{9}")) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "手机号格式错误");
        }
        StpUtil.checkLogin();

        ModifyPhoneEnum phoneEnum = ModifyPhoneEnum.getEnumByType(type);
        if (phoneEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "不支持的操作类型");
        }

        String key = getPhoneKey(phoneEnum, phone);
        Boolean hasKey = stringRedisTemplate.hasKey(key);
        if (hasKey) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请勿重复发送验证码");
        }

        String code = CodeUtils.generate(6);
        log.info("验证码：{}", code);
        stringRedisTemplate.opsForValue().set(key, code, 60, TimeUnit.SECONDS);

        return true;
    }

    private String getPhoneKey(ModifyPhoneEnum phoneEnum, String phone) {
        switch (phoneEnum) {
            case UNBIND:
                return ModifyPhoneConstants.UNBIND_PHONE_KEY + phone;
            case BIND:
                return ModifyPhoneConstants.BIND_PHONE_KEY + phone;
            default:
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "不支持的操作类型");
        }
    }
}
